object CampusAnalyticsSystem extends App {
  // 1. 数据结构定义
  case class DetailedScore(
                            studentId: String,
                            courseId: String,
                            score: Double,
                            semester: String,
                            classRank: Int
                          )
  case class CourseEvaluation(
                               courseId: String,
                               studentId: String,
                               rating: Double,
                               comment: String,
                               date: String
                             )
  case class ResourceUsage(
                            resourceId: String,
                            resourceType: String,
                            userId: String,
                            duration: Double, // 小时
                            date: String
                          )
  case class Department(
                         id: String,
                         name: String,
                         subDepartments: List[Department],
                         facultyCount: Int
                       )
  // 2. 模拟数据（保持与输出匹配）
  val scores = List(
    DetailedScore("S2025001", "C101", 85.0, "2025-I", 5),
    DetailedScore("S2025001", "C102", 90.0, "2025-I", 3),
    DetailedScore("S2025002", "C101", 92.0, "2025-I", 2),
    DetailedScore("S2025002", "C102", 82.0, "2025-I", 7),
    DetailedScore("S2025003", "C101", 76.0, "2025-I", 8),
    DetailedScore("S2025003", "C102", 86.0, "2025-I", 4),
    DetailedScore("S2025001", "C101", 88.0, "2025-II", 4),
    DetailedScore("S2025001", "C102", 92.0, "2025-II", 2),
    DetailedScore("S2025002", "C101", 90.0, "2025-II", 3)
  )
  val evaluations = List(
    CourseEvaluation("C101", "S2025001", 4.5, "老师讲得很好，内容丰富", "2025-06-10"),
    CourseEvaluation("C101", "S2025002", 4.0, "还行，作业有点多", "2025-06-11"),
    CourseEvaluation("C101", "S2025003", 3.5, "一般般，课堂互动少", "2025-06-10"),
    CourseEvaluation("C102", "S2025001", 5.0, "非常好，收获很大", "2025-06-12"),
    CourseEvaluation("C102", "S2025002", 3.0, "内容太难，跟不上", "2025-06-11")
  )
  val resourceUsages = List(
    ResourceUsage("R101", "教室", "T1001", 2.0, "2025-06-01"),
    ResourceUsage("R101", "教室", "T1002", 3.0, "2025-06-03"),
    ResourceUsage("L201", "实验室", "T1001", 4.0, "2025-06-02"),
    ResourceUsage("R101", "教室", "T1001", 2.5, "2025-06-05"),
    ResourceUsage("L201", "实验室", "T1003", 3.5, "2025-06-04")
  )
  val csDept = Department("D101", "计算机系", List(
    Department("D1011", "软件工程", Nil, 15),
    Department("D1012", "计算机科学", Nil, 20)
  ), 0)
  val mathDept = Department("D102", "数学系", List(
    Department("D1021", "应用数学", Nil, 10),
    Department("D1022", "基础数学", Nil, 8)
  ), 0)
  val college = Department("D001", "理工学院", List(csDept, mathDept), 0)
  // 3. 学生成绩分析模块
  object ScoreAnalysis {
    val byStudent = (s: DetailedScore) => s.studentId
    val byCourse = (s: DetailedScore) => s.courseId
    def analyzeScores[T](
                          data: List[DetailedScore],
                          groupFunc: DetailedScore => T,
                          aggFunc: List[DetailedScore] => Double
                        ): Map[T, Double] = {
      data.groupBy(groupFunc).map { case (key, group) =>
        (key, aggFunc(group))
      }
    }
    val averageScore = (group: List[DetailedScore]) =>
      group.map(_.score).sum / group.size

    val maxScore = (group: List[DetailedScore]) =>
      group.map(_.score).max

    def printAnalysis[T](title: String, results: Map[T, Double]): Unit = {
      println(s"=== $title ===")
      results.foreach { case (key, value) =>
        println(f"$key: $value%.1f")
      }
    }
  }
  import ScoreAnalysis._
  val courseAvg = analyzeScores(scores, byCourse, averageScore)
  printAnalysis("各课程平均分", courseAvg)
  val studentMax = analyzeScores(scores, byStudent, maxScore)
  printAnalysis("\n学生最高分", studentMax)
  // 4. 课程评价分析模块
  object EvaluationAnalysis {
    val sentimentAnalyzer: PartialFunction[String, Double] = {
      case comment if comment.contains("好") || comment.contains("收获大") => 0.8
      case comment if comment.contains("一般") || comment.contains("还行") => 0.5
      case comment if comment.contains("少") || comment.contains("跟不上") => 0.2
    }
    val processEvaluation = (eval: CourseEvaluation) => {
      val sentiment = if (sentimentAnalyzer.isDefinedAt(eval.comment)) {
        sentimentAnalyzer(eval.comment)
      } else 0.5
      (eval.rating / 5.0 * 0.5) + (sentiment * 0.5)
    }
    def analyzeCourseEvaluations(data: List[CourseEvaluation]): Map[String, Double] = {
      data.groupBy(_.courseId).map { case (courseId, evals) =>
        val avgScore = evals.map(processEvaluation).sum / evals.size
        (courseId, avgScore)
      }
    }
  }
  import EvaluationAnalysis._
  val courseScores = analyzeCourseEvaluations(evaluations)
  println("\n=== 课程综合评价得分（0-1） ===")
  courseScores.foreach { case (courseId, score) =>
    println(f"$courseId: $score%.2f")
  }
  // 5. 资源使用分析模块（修复报错部分）
  object ResourceAnalysis {
    def analyzeUsageStats(data: List[ResourceUsage]): Map[String, (Int, Double)] = {
      data.groupBy(_.resourceId).map { case (resId, usages) =>
        val count = usages.size
        val totalDuration = usages.map(_.duration).sum
        (resId, (count, totalDuration))
      }
    }
    def printResourceStats(stats: Map[String, (Int, Double)]): Unit = {
      println("\n=== 资源使用统计（次数/总时长） ===")
      stats.foreach { case (resId, (count, duration)) =>
        // 用 ${count} 明确变量，后面直接加"次"文字
        println(f"$resId: ${count}次，$duration%.1f小时")
      }
    }
  }
  import ResourceAnalysis._
  val resourceStats = analyzeUsageStats(resourceUsages) // 调用修复后的方法
  printResourceStats(resourceStats)
  // 6. 组织架构分析模块（可选，如需补充）
  object OrganizationAnalysis {
    def calculateTotalFaculty(dept: Department): Int = {
      @scala.annotation.tailrec
      def countHelper(remaining: List[Department], total: Int): Int = remaining match {
        case Nil => total
        case head :: tail =>
          countHelper(head.subDepartments ++ tail, total + head.facultyCount)
      }
      countHelper(List(dept), 0)
    }
  }
}